<?php
/**
 * Created by PhpStorm.
 * User: Frings
 * Date: 2017-09-24
 * Time: 15:43
 */

namespace app\controllers;


use app\librarys\BaseController;
use app\models\Agent;
use app\models\Area;
use yii\data\Pagination;

class AgentController extends BaseController
{
    public function actionAgentList()
    {
        $request = \Yii::$app->request;
        $count = Agent::getCount();
        $pagination = new Pagination(['totalCount' => $count]);
        $items = Agent::getList($pagination->page, $pagination->pageSize);
        return $this->render('agent-list',
            [
                'items' => $items,
                'pagination' => $pagination
            ]
        );
    }

    public function actionAgentDetailPartial()
    {
        $id = \Yii::$app->request->post('id');
        $item = Agent::getById($id);
        return $this->renderPartial('agent-detail-partial', [
            'item' => $item
        ]);
    }

    public function actionAgentSaveHandler()
    {
        $request = \Yii::$app->request;

        $id = $request->post('id');
        $agent_name = $request->post('agent_name');
        $agent_province_id = $request->post('agent_province_id');
        $agent_city_id = $request->post('agent_city_id');
        $agent_county_id = $request->post('agent_county_id');
        $is_enabled = $request->post('is_enabled');

        $result = Agent::save($id, $agent_name, $agent_province_id, $agent_city_id, $agent_county_id, $is_enabled);
        return $this->renderJson(null, $result ? 0 : 1, $result ? '成功' : '失败');
    }

    public function actionAgentDeleteHandler(){
        $request = \Yii::$app->request;
        $id = $request->post('id');
        $item = Agent::deleteAgentById($id);
        return $this->renderJson($item);
    }

    public function actionGetAreaByLevelHandler()
    {
        $request = \Yii::$app->request;
        $level = $request->post('level');
        $items = Area::getAreaByLevel($level);
        return $this->renderJson($items);
    }

    public function actionGetAreaByParentIdHandler()
    {
        $request = \Yii::$app->request;
        $parent_id = $request->post('parent_id');
        $items = Area::getAreaByParentId($parent_id);
        return $this->renderJson($items);
    }

}